import traceback
from models.hotspot import Hotspot
from extensions import db
from services.platform_crawl_manager import (
    get_platform_latest_crawl_at,
    set_platform_latest_crawl_at,
)
from services.constants import PLATFORM_CONFIG
from services.utils import prepare_hotspot_data
from crawlers.dongchedi import get_hot_search_from_dongchedi


def fetch_dongchedi_hotspot_to_db(crawl_at) -> None:
    """抓取懂车帝热搜数据并存入数据库

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    """
    try:
        # 获取懂车帝热榜数据
        hot_searches = get_hot_search_from_dongchedi()

        new_hot_searches = prepare_hotspot_data(hot_searches, "懂车帝", "热搜", crawl_at)

        # 批量插入数据到数据库
        if new_hot_searches:
            db.session.bulk_insert_mappings(Hotspot, new_hot_searches)
            db.session.commit()

        # 更新平台最新抓取时间
        set_platform_latest_crawl_at("懂车帝", crawl_at)

        print("懂车帝热搜数据抓取并存入数据库成功")

    except Exception as e:
        db.session.rollback()
        print("懂车帝热搜数据抓取并存入数据库失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e


def get_dongchedi_hotspot_from_db() -> list:
    """从数据库获取懂车帝热搜数据

    Parameters:
      crawl_at: 时间戳，用于记录抓取时间

    Returns:
      热榜数据列表
    """
    try:
        # 获取最新抓取时间
        latest_crawl_at = get_platform_latest_crawl_at("懂车帝")

        # 从数据库获取热搜数据
        dongchedi_hotspots = Hotspot.query.filter_by(
            platform=PLATFORM_CONFIG["懂车帝"]["id"],
            section=PLATFORM_CONFIG["懂车帝"]["sections"]["热搜"],
            crawl_at=latest_crawl_at,
        ).all()

        return dongchedi_hotspots

    except Exception as e:
        print("从数据库中获取懂车帝热搜数据失败:", e)
        print("详细错误信息:")
        traceback.print_exc()
        raise e